package com.hmall.api.config;

import com.hmall.api.client.fallback.ItemClientFallback;
import com.hmall.api.client.fallback.PayClientFallback;
import com.hmall.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

//作用是配置FeignClient的日志级别
//这里没加configuration注解是因为在各个client中配置了已经加了
public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.FULL;
    }

    //定义一个请求拦截器，将用户信息传递到请求头，实现在微服务间调用时，将用户信息传递到下游服务
    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //获取登录用户
                Long userId = UserContext.getUser();
                if(userId == null){
                    return;//如果没有登录用户，不传递
                }
                //放入请求头
                requestTemplate.header("user-info", userId.toString());
            }
        };
    }

    //实现ItemClient的fallback
    @Bean
    public ItemClientFallback itemClientFallback(){
        return new ItemClientFallback();
    }
    //实现PayClient的fallback
    @Bean
    public PayClientFallback payClientFallback(){
        return new PayClientFallback();
    }

}